<?php
defined('ROOT_PATH') or exit;

class tag_control extends admin_control {
    public $_mid = 2;
    public $_table = 'article';
    public $_name = '文章';

    function __construct(){
        parent::__construct();

        $this->_mid = max(2, (int)R('mid','R'));
        $models = $this->models->get($this->_mid);
        empty($models) && $this->message(1, '内容不存在！');

        $this->_table = $models['tablename'];
        $this->_name = $models['name'];

        $this->assign('mid',$this->_mid);
        $this->assign('table',$this->_table);
        $this->assign('name',$this->_name);
    }

	// 标签管理
	public function index() {
		// hook admin_tag_control_index_before.php

        $midhtml = $this->cms_content_tag->get_taghtml_mid($this->_mid, 'lay-filter="mid"');
        $this->assign('midhtml',$midhtml);

		$this->display();
	}

    //获取标签列表
    public function get_list(){
        // hook admin_tag_control_get_list_before.php
        //分页
        $page = isset( $_REQUEST['page'] ) ? intval($_REQUEST['page']) : 1;
        $pagenum = isset( $_REQUEST['limit'] ) ? intval($_REQUEST['limit']) : 15;

        //获取查询条件
        $keyword = isset( $_REQUEST['keyword'] ) ? trim($_REQUEST['keyword']) : '';
        if($keyword) {
            $keyword = urldecode($keyword);
            $keyword = safe_str($keyword);
        }

        // 初始模型表名
        $this->cms_content_tag->table = 'cms_'.$this->_table.'_tag';

        //组合查询条件
        $where = array();
        if( $keyword ){
            $where['name'] = array('LIKE'=>$keyword);
        }
        // hook admin_tag_control_get_list_before.php
        //数据量
        if( $where ){
            $total = $this->cms_content_tag->find_count($where);
        }else{
            $total = $this->cms_content_tag->count();
        }

        //页数
        $maxpage = max(1, ceil($total/$pagenum));
        $page = min($maxpage, max(1, $page));

        // 获取标签列表
        $data_arr = array();
        $cms_arr = $this->cms_content_tag->list_arr($where, 'tagid', -1, ($page-1)*$pagenum, $pagenum, $total);
        foreach($cms_arr as &$v) {
            $v['url'] = $this->cms_content->tag_url($this->_mid, $v['name'], $v['tagid']);

            $data_arr[] = $v;   //排序需要索引从0开始
        }
        // hook admin_tag_control_get_list_after.php
        unset($cms_arr);
        //组合数据 输出到页面
        $arr = array(
            'code' => 0,
            'msg' => '',
            'count' => $total,
            'data' => $data_arr,
        );
        exit( json_encode($arr) );
    }

    //编辑表格字段
    public function set(){
        // hook admin_tag_control_set_before.php
        if( !empty($_POST) ){
            $field = trim( R('field','P') );
            $tagid = intval( R('tagid','P') );
            $value = trim( R('value','P') );
            $data = array(
                'tagid' => $tagid,
                $field => $value,
            );
            // 初始模型表名
            $this->cms_content_tag->table = 'cms_'.$this->_table.'_tag';

            if(!$this->cms_content_tag->update($data)) {
                E(1, '更新失败');
            }
            // hook admin_tag_control_set_after.php
            E(0, '更新'.$field.'成功');
        }
    }

	// 添加标签
	public function add() {
        // hook admin_tag_control_add_before.php
        if(empty($_POST)) {
            $midhtml = $this->cms_content_tag->get_taghtml_mid($this->_mid, 'lay-filter="mid"');
            $this->assign('midhtml',$midhtml);

            $data = array(
                'tagid'=>0,
            );

            // hook admin_tag_control_add_after.php
            $this->assign('data',$data);

            $this->display('tag_set.htm');
        }else{
            $name = trim(safe_str(R('name', 'P')));
            $content = htmlspecialchars(trim(R('content', 'P')));

            $batch_name = R('batch_name', 'P');
            $tags_arr = explode(PHP_EOL, $batch_name);
            $tags_arr = array_filter($tags_arr);    //去掉空值
            $tags_arr = array_unique($tags_arr);    //去掉重复

            // hook admin_tag_control_add_post_before.php

            // 初始模型表名
            $this->cms_content_tag->table = 'cms_'.$this->_table.'_tag';

            if($tags_arr){
                $total = count($tags_arr);
                $guolv = $chongfu = $succ = $fail = 0;
                foreach($tags_arr as $name){
                    $name = safe_str($name);
                    if(empty($name) || _strlen($name) > 15){
                        $guolv++;
                        continue;
                    }else{
                        if($this->cms_content_tag->find_fetch(array('name'=>$name), array(), 0, 1)){
                            $chongfu++;
                            continue;
                        }else{
                            $data = array(
                                'name'=>$name,
                                'count'=>0,
                                'content'=>$content,
                                'pic'=>R('pic', 'P'),
                                'seo_title' => trim(strip_tags(R('seo_title', 'P'))),
                                'seo_keywords' => trim(strip_tags(R('seo_keywords', 'P'))),
                                'seo_description' => trim(strip_tags(R('seo_description', 'P')))
                            );

                            if($this->cms_content_tag->create($data)) {
                                $succ++;
                            }else{
                                $fail++;
                            }
                        }
                    }
                }
                $msg = "共{$total}条数据，成功{$succ}条，失败{$fail}条，重复{$chongfu}条，过滤{$guolv}条";
                E(0, $msg);
            }

            empty($name) && E(1, '名称不能为空！');
            _strlen($name)>15 && E(1, '名称太长了！');

            if($this->cms_content_tag->find_fetch(array('name'=>$name), array(), 0, 1)){
                E(1, '标签已经存在啦');
            }

            $data = array(
                'name'=>$name,
                'count'=>0,
                'content'=>$content,
                'pic'=>R('pic', 'P'),
                'seo_title' => trim(strip_tags(R('seo_title', 'P'))),
                'seo_keywords' => trim(strip_tags(R('seo_keywords', 'P'))),
                'seo_description' => trim(strip_tags(R('seo_description', 'P')))
            );

            // hook admin_tag_control_add_post_after.php

            if($this->cms_content_tag->create($data)) {
                E(0, '添加成功！');
            }else{
                E(1, '添加失败！');
            }
        }
	}

	//编辑
    public function edit(){
        // hook admin_tag_control_edit_before.php

	    if(empty($_POST)){
            $midhtml = $this->cms_content_tag->get_taghtml_mid($this->_mid, 'lay-filter="mid"');
            $this->assign('midhtml',$midhtml);

            $tagid = intval( R('tagid','G') );

            // 初始模型表名
            $this->cms_content_tag->table = 'cms_'.$this->_table.'_tag';
            $data = $this->cms_content_tag->get($tagid);
            $this->assign('data',$data);

            $this->display('tag_set.htm');
        }else{
            $tagid = (int)R('tagid','P');

            $name = trim(safe_str(R('name', 'P')));
            $content = htmlspecialchars(trim(R('content', 'P')));

            empty($name) && E(1, '名称不能为空！');
            _strlen($name)>15 && E(1, '名称太长了！');

            // 初始模型表名
            $this->cms_content_tag->table = 'cms_'.$this->_table.'_tag';

            $tagold = $this->cms_content_tag->get($tagid);
            empty($tagold) &&  E(1, '标签不存在！');

            if($tagold['name'] != $name && $this->cms_content_tag->find_fetch(array('name'=>$name), array(), 0, 1)){
                E(1, '标签已经存在啦');
            }

            // 修改 cms_content 表的内容
            if($tagold['name'] != $name) {
                $this->cms_content->table = 'cms_'.$this->_table;
                $this->cms_content_tag_data->table = 'cms_'.$this->_table.'_tag_data';

                $list_arr = $this->cms_content_tag_data->find_fetch(array('tagid'=>$tagid));
                foreach($list_arr as $v) {
                    $data2 = $this->cms_content->read($v['id']);
                    if(empty($data2)){
                        $this->cms_content_tag_data->find_delete(array('tagid'=>$tagid, 'id'=>$v['id']));
                    }else{
                        $row = _json_decode($data2['tags']);
                        $row[$tagid] = $name;

                        $up_data2['id'] = $v['id'];
                        $up_data2['tags'] = _json_encode($row);
                        $this->cms_content->update($up_data2);
                    }
                }
            }

            $data = array(
                'tagid'=>$tagid,
                'name'=>$name,
                'content'=>$content,
                'pic'=>R('pic', 'P'),
                'seo_title' => trim(strip_tags(R('seo_title', 'P'))),
                'seo_keywords' => trim(strip_tags(R('seo_keywords', 'P'))),
                'seo_description' => trim(strip_tags(R('seo_description', 'P')))
            );

            // hook admin_tag_control_edit_after.php

            if($this->cms_content_tag->update($data)) {
                E(0, '编辑成功！');
            }else{
                E(1, '编辑失败！');
            }
        }
    }

	// 删除
	public function del() {
		// hook admin_tag_control_del_before.php

		$tagid = (int) R('tagid', 'P');
		empty($tagid) && E(1, '标签ID不能为空！');

        // 初始模型表名
        $this->cms_content_tag->table = 'cms_'.$this->_table.'_tag';
		$err = $this->cms_content_tag->xdelete($this->_table, $tagid);
		if($err) {
			E(1, $err);
		}else{
            // hook admin_tag_control_del_success.php
			E(0, '删除成功！');
		}
	}

	// 批量删除
	public function batch_del() {
		// hook admin_tag_control_batch_del_before.php
		$id_arr = R('id_arr', 'P');

		if(!empty($id_arr) && is_array($id_arr)) {
            // 初始模型表名
            $this->cms_content_tag->table = 'cms_'.$this->_table.'_tag';

			$err_num = 0;
			foreach($id_arr as $tagid) {
				$err = $this->cms_content_tag->xdelete($this->_table, $tagid);
				if($err) $err_num++;
			}

			if($err_num) {
				E(1, $err_num.' 条标签删除失败！');
			}else{
				E(0, '删除成功！');
			}
		}else{
			E(1, '参数不能为空！');
		}
	}

	// hook admin_tag_control_after.php
}
